/**
*
* Non Preemptive Fixed Priority
* see <a href="{@docRoot}/Documentation/scheduler.html"> for more information</a>
*  Copyright (c) 2009 Ecole Centrale de Nantes IRCCyN
* @author: amd
* @version
*/
package storm.Schedulers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import storm.EvtContext;
import storm.Processors.Processor;
import storm.Tasks.Task;

/**
 * @author amd
 * Non Preemptive Fixed Priority
 * Cf. Reunion du 13/01
 *
 */
public class FP_NP_Scheduler extends Scheduler {
	/**
	 * 
	 * 
	 *
	 */
	class LReady extends ArrayList implements Comparator {

		public int compare(Object arg0, Object arg1) {
			Task T0 = (Task) arg0;
			Task T1 = (Task) arg1;
			if (T0.priority > T1.priority) return -1;
			else if (T0.priority == T1.priority) return 0;
			     else return 1;
		}
		
	}
	/**
	 * 
	 */
	private LReady list_ready;
	private Boolean todo = false;
	/**
	 * 
	 */
	public void init() {
		super.init();
		list_ready = new LReady();
	}
	/**
	 * 
	 */
	public void onActivate(EvtContext c) {
		list_ready.add(c.getCible());
		ArrayList CPUS =this.Kernel.getTasksListeManager().getProcessors();
		if (list_ready.size() <= CPUS.size()) todo = true;
	}
	/**
	 * 
	 */
	public void onUnBlock(EvtContext c){
		list_ready.add(c.getSource());
		ArrayList CPUS =this.Kernel.getTasksListeManager().getProcessors();
		if (list_ready.size() <= CPUS.size()) todo = true;
	}
	/**
	 * 
	 */
	public void onBlock(EvtContext c){
		//System.out.println(list_ready.size());
		list_ready.remove(c.getCible());
		//System.out.println(list_ready.size());
		Task T = (Task) c.getCible();
		if (T.predStateIsRunning()) todo = true;
	}
	/**
	 * 
	 */
	public void onTerminated(EvtContext c){
		

		//System.out.println(list_ready.size());
		list_ready.remove(c.getCible());
	
		//System.out.println(list_ready.size());
		Task T = (Task) c.getCible();
		if (T.predStateIsRunning()) todo = true;
	}
	/**
	 * 
	 */
	public void sched(){
		if (todo) {
			select();
			todo = false;
		}
	}
	/**
	 * 
	 */
	public void select() {

		Collections.sort(list_ready,list_ready);
		ArrayList CPUS =this.Kernel.getTasksListeManager().getProcessors();
		int m = CPUS.size();
		int j = 0;
		for (int i=0; (i<m) && (i<list_ready.size()); i++){
			Task T = (Task) list_ready.get(i);

			if (!T.isIsrunning()) {

				Processor P = null;
				for (; j<m; j++){
					P = (Processor) CPUS.get(j);

					if (!P.isRunning()) {
						j++;
						break;
					}
				}
				

				T.runningOn(P);
			}
		}

	}
}
